package com.hongye.controller;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFDataFormat;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

import com.hongye.app.controller.UserAppInfoController;
import com.hongye.app.model.GoodsCategroyModel;
import com.hongye.app.model.GoodsModel;
import com.hongye.app.model.UserAppModel;
import com.hongye.util.PushUtils;
import com.hongye.util.Utils;
import com.jfinal.core.Controller;
import com.jfinal.render.RenderException;
import com.jfinal.upload.UploadFile;

/**
 * 商品相关
 * @author changpf  at 2016年9月17日16:24:51
 *
 */
public class GoodsController extends Controller {
	private static final String DocPath = "C:/MyPro/apache-tomcat-7.0.70/webapps/rbg/doc/";//下载路径
	
	public GoodsController() {
	}
	
	/**
	 * 商品审核
	 */
	public void goodsReview(){
		String sql = "select *,a.id as goodsid from goods a ,buyer b ,buyer_statistics bs WHERE a.`seller_id`=b.`user_id` and b.user_id = bs.buyer_id order by audit, c_time DESC";
		List<GoodsModel> lst = GoodsModel.dao.find(sql);
		this.setAttr("goodsReview",lst);
		this.renderJsp("goodsReview.jsp");
	}
	
	/**
	 * 商品详情. add by changpf at 2016年9月17日20:00:11
	 */
	public void goodsDetail(){
		GoodsModel goodsDetail=GoodsModel.dao.getGoodsDetail(null, this.getPara("gid"));
		this.setAttr("goodsDetail", goodsDetail);
		this.setAttr("gid", this.getPara("gid"));
		this.setAttr("GoodsCategroy", GoodsCategroyModel.getCategroyName(goodsDetail.getInt("c_id").toString()).get("c_name"));
		this.renderJsp("goodsDetail.jsp");
	}
	
	/**
	 * 更新商品状态. add by changp 2016年9月18日22:53:11
	 */
	public void updateGoodsState(){
		String gid=getPara("gid");
		String state=getPara("state");
		String reason=getPara("reason");
		String rs="suc";
		GoodsModel goodsmodel = GoodsModel.dao.findById(gid);
		UserAppModel us = UserAppModel.dao.findById(goodsmodel.get("seller_id"));
		if(state.equals("1")){
			if(goodsmodel.set("audit", state).set("sale", 0).set("n_reason", reason).update()){
				PushUtils.MSG_Single(us.getStr("phone"), "D02", "您的商品审核通过啦！去看看吧！");
			}else{
				rs="err";
			}
		}else if(state.equals("2")){
			if(goodsmodel.set("audit", state).set("n_reason", reason).update()){
				PushUtils.MSG_Single(us.getStr("phone"), "D01", "您的商品审核未通过，请查看原因修改后再上传！");
			}else{
				rs="err";
			}
		}
		this.renderText(rs);
	}
	
	/**
	 * 类别管理-管理端
	 * @author lifuqiang
	 * 2016-10-7
	 */
	public void goodsCategroyView(){
		String sql = "select * from goods_categroy order by pid";
		List<GoodsCategroyModel> lis = GoodsCategroyModel.dao.find(sql);
		List<GoodsCategroyModel> list = new ArrayList<GoodsCategroyModel>();
		this.setAttr("goodscategroy", lis);
		this.setAttr("list", list);
		this.renderJsp("goodsCategroyView.jsp");
	}
	
	/**
	 * 商品类别详细
	 * @author lifuqiang
	 * 2016-10-10
	 */
	public void categroydetail(){
		String pid = this.getPara("pid");
		String sql = "select * from goods_categroy where pid='"+pid+"'";
		GoodsCategroyModel catedetail = GoodsCategroyModel.dao.findFirst(sql);
		this.setAttr("catedetail", catedetail);
		this.setAttr("id", catedetail.get("id"));
		this.renderJsp("categroyDetail.jsp");
	}
	
	/**
	 * 添加商品类别
	 * @author lifuqiang
	 * 2016-10-9
	 */
	public void addCategroy(){
		String catename = this.getPara("name");
		String pid = this.getPara("pid");
		String sql = "select * from goods_categroy where pid= '"+pid+"' and c_name='"+catename+"'";
		GoodsCategroyModel goodscate = GoodsCategroyModel.dao.findFirst(sql);
		String rs = null;
		if(goodscate==null){
			if(new GoodsCategroyModel().set("c_name", catename).set("showg", 0).set("pid", pid).save()){
				rs = "suc";
			}else{
				rs = "fal";
			}
		}else{
			rs = "re";
		}
		this.renderText(rs);
	}
	/**
	 * 修改类别
	 * @author lifuqiang
	 * 2016-10-10
	 */
	public void editCategroy(){
		String id = this.getPara("id");
		String catename = this.getPara("name");
		String pid = this.getPara("pid");
		String showg = this.getPara("showg");
		String sql = "select * from goods_categroy where id='"+id+"'";
		GoodsCategroyModel goodscate = GoodsCategroyModel.dao.findFirst(sql);
		String rs = null;
		if(goodscate!=null){
			if(goodscate.set("c_name", catename).set("showg", showg).set("pid", pid).update()){
				rs = "suc";
			}else{
				rs = "fal";
			}
		}else{
			rs = "re";
		}
		this.renderText(rs);
	}
	
	/**
	 * 通过一级分类获取二级分类
	 * @author lifuqiang
	 * 2016-12-26
	 */
	public void get2Categroy(){
		String pid = this.getPara("pid");
		String sql = "select * from goods_categroy where pid = "+pid+"";
		String sql2 = "select * from goods_categroy order by pid";
		List<GoodsCategroyModel> catelist = GoodsCategroyModel.dao.find(sql2);
		GoodsCategroyModel cate = GoodsCategroyModel.dao.findFirst(sql);
		List<GoodsCategroyModel> list = new ArrayList<GoodsCategroyModel>();
		for (GoodsCategroyModel goodsCategroyModel : catelist) {
			if(goodsCategroyModel.getInt("pid")>cate.getInt("pid")*100 && goodsCategroyModel.getInt("pid")<(cate.getInt("pid")+1)*100){
				list.add(goodsCategroyModel);
			}
		}
		this.setAttr("list", list);
		this.setAttr("goodscategroy", catelist);
		this.renderJsp("goodsCategroyView.jsp");
	}

	/**
	 * 热播狗自营商品列表展示
	 * @author liushaomin
	 * 2017年8月17日
	 */
	public void rbggoodsReview(){
		String sql = "select *,id as goodsid from goods WHERE seller_id = 61 order by c_time DESC";
		List<GoodsModel> lst = GoodsModel.dao.find(sql);
		String[] ids = new String[lst.size()];
		for (int i = 0; i < ids.length; i++) {
			int id = lst.get(i).get("id");
			ids[i] = String.valueOf(id);
		}
		this.setAttr("goodsReview",lst);
		this.setAttr("ids", Arrays.toString(ids));
		this.renderJsp("rbgGoodsReview.jsp");
	}


	/**
	 * 热播狗自营商品编辑页面
	 * @author liushaomin
	 * 2017年8月17日
	 */
	public void rbgGoodsDetail(){
		GoodsModel goodsDetail=GoodsModel.dao.getGoodsDetail(null, this.getPara("gid"));
		this.setAttr("goodsDetail", goodsDetail);
		this.setAttr("gid", this.getPara("gid"));
		this.setAttr("GoodsCategroy", GoodsCategroyModel.getCategroyName(goodsDetail.getInt("c_id").toString()).get("c_name"));
		this.renderJsp("rbgGoodsDetail.jsp");
	}
	
	/**
	 * 更新热播购商品信息
	 * @author liushaomin
	 * 2017年8月18日
	 */
	public void rbgUpdateGoodsState(){
		String gid = getPara("gid");
		String goodsname = getPara("goodsname");
		String real_price = getPara("real_price");
		String content = getPara("content");
		String rs="err";
		GoodsModel goodsmodel = GoodsModel.dao.findById(gid);
		boolean boo = goodsmodel.set("g_name", goodsname).set("real_price",real_price).set("content", content).update();
		if(boo){
			rs="suc";
		}
		this.renderText(rs);
	}
	
	/**
	 * ckeditor 上传图片
	 * @author liushaomin
	 * 2017年9月7日
	 */
	public void rbgGoodsDetailImg() {
        String path = "ZYGoodsImg/";
        UploadFile file = getFile("upload", path);
        Long fileName = System.currentTimeMillis();
        if(null!=file){
            String sufName = file.getFileName().substring(file.getFileName().lastIndexOf("."),file.getFileName().length());
            File dest = new File("C:/MyPro/apache-tomcat-7.0.70/webapps/rbg/upload/ZYGoodsImg" + File.separator + fileName + sufName);
            file.getFile().renameTo(dest);
            String callback =getPara("CKEditorFuncNum"); 
            PrintWriter writer = null;
            String imgpath = UserAppInfoController.ImgPath + path + fileName + sufName;
            try {
                HttpServletResponse response = getResponse();
                writer = response.getWriter();
                writer.write("<script type=\"text/JavaScript\">"
                        +"window.parent.CKEDITOR.tools.callFunction("+ callback + ",'" + imgpath +"','')"
                        +"</script>");
                writer.flush();
            } catch (IOException e) {
                throw new RenderException(e);
            }
            finally {
                if (writer != null)
                    writer.close();
            }
        }
        renderNull();
    }
	
	
	/**
	 * 调用下载
	 * @author lifuqiang
	 * 2016-12-21
	 * @throws Exception 
	 */
	public void rbgdownload(){
		String idstr = this.getPara("ids");
		String[] ids = idstr.substring(1, idstr.length()-1).split(", ");
		try {
			exportexcel(ids,this.getResponse());
		} catch (Exception e) {
			e.printStackTrace();
		}
		this.renderNull();
	}
	
	/**
	 * 下载交易信息到Excel
	 * @author lifuqiang
	 * 2016-12-21
	 */
	@SuppressWarnings("resource")
	public void exportexcel(String[] ids, HttpServletResponse response) throws Exception{
		HSSFWorkbook wb = new HSSFWorkbook();
		HSSFSheet sheet = wb.createSheet("商品统计表.xls");//创建一个工作表aa.xls
		sheet.setColumnWidth(0, 3000);//设置列宽
		sheet.setColumnWidth(1, 8000);
		sheet.setColumnWidth(2, 12000);
		sheet.setColumnWidth(3, 3000);
		sheet.setColumnWidth(4, 3000);
		sheet.setColumnWidth(5, 3000);
		sheet.setColumnWidth(6, 5000);
		sheet.setColumnWidth(7, 5000);
		sheet.setColumnWidth(8, 5000);
		sheet.setColumnWidth(9, 5000);
		HSSFCellStyle style = wb.createCellStyle();//获取单元格样式对象
		style.setAlignment(HSSFCellStyle.ALIGN_CENTER);//设置居中
		style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
		
        HSSFRow row = sheet.createRow((int) 0); // 开始填充数据
		HSSFCell cellScore = null;
		short colNum = 0;// 列起始
		cellScore = row.createCell(0);   //设置表头
		cellScore.setCellValue("序号");  
		cellScore.setCellStyle(style);  
		cellScore = row.createCell(1);  
		cellScore.setCellValue("编号");  
		cellScore.setCellStyle(style);  
        cellScore = row.createCell(2);  
        cellScore.setCellValue("名称");  
        cellScore.setCellStyle(style);  
        cellScore = row.createCell(3);  
        cellScore.setCellValue("价格（元）");  
        cellScore.setCellStyle(style);  
        cellScore = row.createCell(4);  
        cellScore.setCellValue("上传时间");  
        cellScore.setCellStyle(style);  
        cellScore = row.createCell(5);  
        cellScore.setCellValue("类别");  
        cellScore.setCellStyle(style);  
		cellScore = row.createCell(6);  
        cellScore.setCellValue("条形码");
        cellScore.setCellStyle(style);
		List<GoodsModel> list = new ArrayList<GoodsModel>();
		for (int i = 0; i < ids.length; i++) {
			list.add(GoodsModel.getGoodsById(Integer.valueOf(ids[i])));
		}
		for (int i = 0; i < list.size(); i++) {
			int nclo = colNum;
			row = sheet.createRow(i + 1);
			HSSFCell cell = row.createCell(0);
			cell.setCellValue(i+1);
			cellScore = row.createCell(nclo++);
			cellScore.setCellType(HSSFCell.CELL_TYPE_NUMERIC);
			cellScore.setCellValue(i);
			cellScore.setCellStyle(style);
			
			cellScore = row.createCell(nclo++);
			cellScore.setCellType(HSSFCell.CELL_TYPE_NUMERIC);
			cellScore.setCellValue(list.get(i).getInt("id").toString());
			cellScore.setCellStyle(style);
			
			cellScore = row.createCell(nclo++);
			cellScore.setCellType(HSSFCell.CELL_TYPE_NUMERIC);
			cellScore.setCellValue(list.get(i).getStr("g_name"));
			cellScore.setCellStyle(style);
			
			cellScore = row.createCell(nclo++);
			cellScore.setCellType(HSSFCell.CELL_TYPE_NUMERIC);
			cellScore.setCellValue(list.get(i).get("real_price").toString());
			cellScore.setCellStyle(style);
			
			cellScore = row.createCell(nclo++);
			cellScore.setCellType(HSSFCell.CELL_TYPE_NUMERIC);
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			cellScore.setCellValue(Utils.sdfToDate(list.get(i).get("c_time").toString(), sdf));
			HSSFCellStyle cellStyle = wb.createCellStyle();
            HSSFDataFormat format= wb.createDataFormat();
            cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);//设置居中
            cellStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
            cellStyle.setDataFormat(format.getFormat("yyyy/MM/dd HH:mm:ss"));
            cellScore.setCellStyle(cellStyle);
			
            cellScore = row.createCell(nclo++);
			cellScore.setCellType(HSSFCell.CELL_TYPE_NUMERIC);
			cellScore.setCellValue(GoodsCategroyModel.getCategroyName(list.get(i).getInt("c_id").toString()).getStr("c_name"));
			cellScore.setCellStyle(style);
			
			cellScore = row.createCell(nclo++);
			cellScore.setCellType(HSSFCell.CELL_TYPE_NUMERIC);
			cellScore.setCellValue("");
			cellScore.setCellStyle(style);
		}
		
		String fileName = "自营商品统计表.xls";
		String myExcel = DocPath;
		String filePath = myExcel + fileName;
		FileOutputStream out = new FileOutputStream(filePath);// 创建xls文件
		wb.write(out);
		out.close();
		File file = new File(filePath);
		Utils.download(response, file, fileName);
	}
}
